﻿using EMoney.IStock.Client.Business.MC;
using EMoney.IStock.Client.Core;
using EMoney.IStock.Client.DataAccess.CQ;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models;
using EMoney.IStock.Client.Models.CQ;
using EMoney.IStock.Client.Models.MC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using ThinkDev.Logging;
using System.Linq.Dynamic;

namespace EMoney.IStock.Client.Business.CQ
{
    /// <summary>
    /// 竞猜信息业务处理类
    /// </summary>
    public class MyGuessBll
    {
        private const string MYGUESS_CACHED_KEY = "EMoney.IStock.Client.Business.CQ.MyGuessBll.MyGuess";

        /// <summary>
        /// 获取竞猜日期
        /// </summary>
        /// <returns></returns>
        public DateTime GetGuessDate(out bool canGuess)
        {
            canGuess = true;

            if (!string.IsNullOrEmpty(ConfigHelper.CQGuessDate))
            { 
                DateTime dtTemp = DateTime.MinValue;

                if (DateTime.TryParse(ConfigHelper.CQGuessDate, out dtTemp))
                {
                    return dtTemp;
                }
            }
            
            DateTime dtNow = DateTime.Now;
            DateTime dtGuessDate = DateTime.MinValue;

            if (TradeDateBll.IsTradeDate(dtNow.Date))   //当天为交易日
            {
                if (dtNow.TimeOfDay <= new TimeSpan(9, 15, 0))  //9:15分前竞猜日期为当天
                {
                    dtGuessDate = dtNow;
                }
                else if (dtNow.TimeOfDay > new TimeSpan(9, 15, 0) && dtNow.TimeOfDay < new TimeSpan(15, 30, 0)) //提示不在竞猜时间
                {
                    canGuess = false;
                    dtGuessDate = dtNow;
                }
            }

            if (dtGuessDate == DateTime.MinValue)    //竞猜日期为下一交易日
            {
                dtGuessDate = TradeDateBll.GetNextTradeDate(dtNow);
            }

            return dtGuessDate.Date;
        }

        /// <summary>
        /// 获取传奇用户信息
        /// </summary>
        /// <returns></returns>
        public MyGuess GetCQ()
        {
            int cqUserID = CacheManager.DefaultCache.Get<int>(GuessConstDefine.CQ_CACHED_KEY);

            if (cqUserID > 0)
            {
                return GetMyGuess(cqUserID);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取用户竞猜信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public MyGuess GetMyGuess(int userid,string ip = "")
        {
            bool canGuess = false;
            DateTime dtGuessDate = GetGuessDate(out canGuess);

            string key = string.Concat(MYGUESS_CACHED_KEY, ".", userid,".",StringHelper.FormatDateTime(dtGuessDate));

            MyGuess myGuess = CacheManager.RedisCache.Get<MyGuess>(key);

            if (myGuess == null || myGuess.TradeDate < Convert.ToDateTime("2014-8-15"))
            {
                try
                {
                    myGuess = new MyGuess() { 
                        UserID = userid,
                        TradeDate = DateTime.MinValue
                    };

                    MyGuessDal myGuessDal = new MyGuessDal();

                    myGuess.GuessTotalCount = myGuessDal.GetGuessCount(userid, -1);      //总竞猜数
                    myGuess.CorrectGuessCount = myGuessDal.GetGuessCount(userid, 1);     //猜中次数

                    MyGuess newestGuess = myGuessDal.GetNewestGuess(userid);    //获取用户最新的竞猜信息

                    if (newestGuess != null)
                    {
                        myGuess.TradeDate = newestGuess.TradeDate;
                        myGuess.GuessType = newestGuess.GuessType;
                        myGuess.GuessResult = newestGuess.GuessResult;
                        myGuess.IsPromotion = newestGuess.IsPromotion;
                        myGuess.GuessTime = newestGuess.GuessTime;
                    }

                    ContinueGuessDal continueGuessDal = new ContinueGuessDal();

                    myGuess.ContinueCorrectGuessCount = continueGuessDal.GetMaxContinueDays(userid, 1); //连续猜对
                    myGuess.ContinueErrorGuessCount = continueGuessDal.GetMaxContinueDays(userid, 0);   //连续猜错

                    CacheManager.RedisCache.Set<MyGuess>(key, myGuess, 60 * 24);
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), string.Concat("获取用户竞猜信息失败.", userid));
                }
            }

            if (myGuess != null)
            {
                MyInfoBll myInfoBll = new MyInfoBll();

                MC_MyInfo myInfo = myInfoBll.GetMyInfo(myGuess.UserID);

                if (myInfo != null)
                {
                    myGuess.UserName = myInfo.UserName;
                    myGuess.UserPic = myInfo.UserPic;
                    myGuess.UserPicUrl = myInfoBll.GetUserPic(77, myInfo.UserPic);
                }

                myGuess.GuessTypeStat = GetGuessType(myGuess.TradeDate);
            }

            return myGuess;
        }

        /// <summary>
        /// 竞猜
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="guessDate">竞猜日期</param>
        /// <param name="guessType">1:看涨 0:看跌</param>
        /// <returns></returns>
        public string Guess(int userid, DateTime guessDate, int guessType)
        {
            if (GetCQ() != null)    //存在竞猜第一名的信息
            {
                return string.Empty;
            }

            bool canGuess = false;
            string ret = string.Empty;
            
            DateTime dtGuessDate = GetGuessDate(out canGuess);

            if (canGuess)   //处于竞猜时间
            {
                if (dtGuessDate.Date != guessDate.Date) //传入的竞猜日期与当前的竞猜日期不同
                {
                }
                else
                {
                    try
                    {
                        MyGuessDal myGuessDal = new MyGuessDal();

                        if (myGuessDal.GetMyGuess(userid, guessDate) == null)   //该交易日未竞猜
                        {
                            if (myGuessDal.AddMyGuess(new MyGuess()
                            {
                                GuessTime = DateTime.Now,
                                GuessType = guessType,
                                TradeDate = guessDate,
                                UserID = userid
                            }) == 1)    //新增竞猜信息成功
                            {
                                ret = "1";

                                MyGuess myGuess = GetMyGuess(userid);

                                if (myGuess != null)
                                {
                                    myGuess.GuessTotalCount = myGuessDal.GetGuessCount(userid, -1);      //总竞猜数
                                    myGuess.TradeDate = guessDate;
                                    myGuess.GuessType = guessType;
                                    myGuess.GuessResult = null;
                                    myGuess.GuessTime = DateTime.Now;

                                    SetMyGuess(myGuess, dtGuessDate);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), string.Concat("竞猜失败.", userid, ".", StringHelper.FormatDateTime(guessDate), ".", guessType));
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 设置个人信息缓存
        /// </summary>
        /// <param name="myInfo"></param>
        public void SetMyGuess(MyGuess myGues,DateTime dtGuess)
        {
            if (myGues != null)
            {
                string key = string.Concat(MYGUESS_CACHED_KEY, ".", myGues.UserID,".",StringHelper.FormatDateTime(dtGuess));

                CacheManager.RedisCache.Set<MyGuess>(key, myGues, 60 * 24);
            }
        }

        /// <summary>
        /// 获取总的竞猜人数
        /// </summary>
        /// <returns></returns>
        public GuessTotal GetGuessUserCount()
        {
            return CacheManager.DefaultCache.Get<GuessTotal>(GuessConstDefine.TOTALCOUNT_CACHED_KEY);
        }

        /// <summary>
        /// 晋级出局人数
        /// </summary>
        /// <returns></returns>
        public PromotionOutCount GetPromotionOutCount()
        {
            List<PromotionOutCount> list = CacheManager.DefaultCache.Get<List<PromotionOutCount>>(GuessConstDefine.PROMOTIONOUTCOUNT_CACHED_KEY);

            if (list != null && list.Count > 0)
            {
                bool canGuess = false;
                DateTime dtGuessDate = GetGuessDate(out canGuess);

                return list.Find(lst => lst.TradeDate == TradeDateBll.GetPreTradeDate(dtGuessDate));
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取竞猜日期的前一交易日竞猜结果
        /// </summary>
        /// <returns></returns>
        public GuessResult GetGuessResult()
        {
            List<GuessResult> resultList = CacheManager.DefaultCache.Get<List<GuessResult>>(GuessConstDefine.GUESSRESULT_CACHED_KEY);

            if (resultList != null && resultList.Count > 0)
            {
                bool canGuess = false;
                DateTime dtGuessDate = GetGuessDate(out canGuess);
                return resultList.Find(lst => lst.TradeDate == TradeDateBll.GetPreTradeDate(dtGuessDate));
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取指定交易日竞猜记录
        /// </summary>
        /// <param name="tradeDate"></param>
        /// <returns></returns>
        public GuessType GetGuessType(DateTime tradeDate)
        {
            List<GuessType> typeList = CacheManager.DefaultCache.Get<List<GuessType>>(GuessConstDefine.GUESSTYPE_CACHED_KEY);

            if (typeList != null && typeList.Count > 0)
            {
                return typeList.Find(lst => lst.TradeDate == tradeDate);
            }
            else
            {
                return null;
            }
        }
    }
}
